﻿using UnityEngine;
using UnityEngine.UI;

public class UIMgr : BaseMono
{
	public static UIMgr Ins;

	public Button StartButton;

	public GameObject GameResult;

	public GameObject Win;
	public Button NextLevel;

	public GameObject Lose;
	public Button RestartButton;
	public Button Quit;
	public Text ResultText;

	public PlayerInfosUI PlayerInfosUI;


	public override void onAwake()
	{
		Ins = this;
		base.onAwake();
		StartButton.onClick.AddListener(StartGame);

		NextLevel.onClick.AddListener(ChooseNextLevel);
		RestartButton.onClick.AddListener(Restart);
		Quit.onClick.AddListener(QuitGame);

		HideResult();
		PlayerInfosUI.SetVisible(false);
	}

	public override void onEnable()
	{
		base.onEnable();
		EventMgr.Ins.RegistEvent(GameState.GameEnd, ShowResult);
	}

	public override void onDisable()
	{
		base.onDisable();
		EventMgr.Ins.RemoveEvent(GameState.GameEnd, ShowResult);
	}

	public void StartGame()
	{
		StartButton.gameObject.SetActive(false);
		PlayerInfosUI.SetVisible(true);
		MainGame.Ins.StartGame();
	}

	public void Restart()
	{
		HideResult();
		MainGame.Ins.RestartGame();
		PlayerInfosUI.Reset();
	}

	public void ChooseNextLevel()
	{
		MainGame.Ins.SelectNextLeve(b =>
		{
			if (b)
			{
				HideResult();
				PlayerInfosUI.Reset();
			}
			else
			{
				MyLog.LogError("No More Levels");
			}
		});
	}

	public void ShowResult(object[] args = null)
	{
		bool win = (bool)args[0];
		string result = win ? "You Win !" : "Game Over !";
		ResultText.text = result;

		if (win)
		{
			Win.SetActive(true);
			Lose.SetActive(false);
		}
		else
		{
			Win.SetActive(false);
			Lose.SetActive(true);
		}
		GameResult.SetActive(true);
	}

	public void HideResult()
	{
		GameResult.SetActive(false);
	}

	public void QuitGame()
	{
		Application.Quit();
	}
}
